package ${projectDomain}.adapter.system;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import ${projectDomain}.adapter.BaseAdapter;
import ${projectDomain}.mapper.system.department.SystemDepartmentExtendMapper;
import ${projectDomain}.mapper.system.department.SystemDepartmentMapper;
import ${projectDomain}.pojo.dao.sql.Sql;
import ${projectDomain}.pojo.dao.system.department.SystemDepartmentDataDo;
import ${projectDomain}.pojo.dao.system.department.SystemDepartmentInsertDo;
import ${projectDomain}.pojo.dao.system.department.SystemDepartmentSearchDo;
import ${projectDomain}.pojo.dao.system.department.SystemDepartmentSingleDo;
import ${projectDomain}.pojo.vo.system.department.SystemDepartmentTreeVo;
import com.unswift.utils.ExceptionUtils;
import com.unswift.utils.ObjectUtils;
import com.unswift.utils.StringUtils;

@Component
@Api(value="部门公共服务-此bean可以被任何Service引用", author="liyunlong", date="2024-01-11", version="1.0.0")
public class SystemDepartmentAdapter extends BaseAdapter{
	
	@Autowired
	@ApiField("部门数据库操作对象")
	private SystemDepartmentMapper systemDepartmentMapper;
	
	@Autowired
	@ApiField("部门数据库扩展操作对象")
	private SystemDepartmentExtendMapper systemDepartmentExtendMapper;
	
	@ApiMethod(value="获取部门数据库操作对象", returns=@ApiField("数据库操作对象"))
	public SystemDepartmentMapper getMapper(){
		return systemDepartmentMapper;
	}
	
	@ApiMethod(value="获取部门模块名称", returns=@ApiField("模块名称"))
	public String getModule(){
		return "systemDepartment";
	}
	
	@ApiMethod(value="根据主键查询单个对象", params=@ApiField("主键"), returns=@ApiField("主键匹配的对象"))
	public SystemDepartmentDataDo findById(Long id){
		return this.findSingle(new SystemDepartmentSingleDo(id, null));
	}
	
	@ApiMethod(value="根据主键列表查询列表对象", params=@ApiField("主键列表"), returns=@ApiField("主键列表匹配的列表对象"))
	public List<SystemDepartmentDataDo> findByIds(List<Long> idList){
		return this.findList(new SystemDepartmentSearchDo(idList));
	}
	
	@ApiMethod(value="根据查询对象查询首个对象", params={@ApiField("查询对象"), @ApiField("查询到多个是否抛出异常，可以传入指定提示语，如果提示语为空，则不提示，总的提示与格式：根据%s查询到多条数据，只需要传递%s部分即可")}, returns=@ApiField("首个对象"))
	public SystemDepartmentDataDo findFirst(SystemDepartmentSearchDo search, String multipleException){
		List<SystemDepartmentDataDo> list=this.findList(search);
		if(ObjectUtils.isEmpty(list)){
			return null;
		}
		if(ObjectUtils.isNotEmpty(multipleException)){
			ExceptionUtils.trueException(list.size()>1, "multiple.data.found", multipleException);
		}
		return list.get(0);
	}
	
	@ApiMethod(value="查找父资源，如果当前列表不包含完整路径的资源，则会补齐", params = {@ApiField("资源列表"), @ApiField("资源列表的主键集合")})
    public void findParent(List<SystemDepartmentDataDo> list, Set<Long> havingIdSet) {
    	if(ObjectUtils.isNotEmpty(list)) {
    		List<SystemDepartmentDataDo> otherList=new ArrayList<SystemDepartmentDataDo>();
    		Set<Long> otherIdSet=new HashSet<Long>();
    		String parentPath;
    		String[] parentPathArray;
    		long parentId;
    		for (SystemDepartmentDataDo department : list) {
				if(ObjectUtils.isEmpty(department.getParentId())) {
					continue;
				}
				parentPath=department.getParentPath();
				parentPath=parentPath.substring(1, parentPath.length()-1);
				parentPathArray=parentPath.split("\\.");
				for (String item : parentPathArray) {
					parentId=Long.parseLong(item);
					if(!havingIdSet.contains(parentId) && !otherIdSet.contains(parentId)) {
						otherList.add(this.findById(parentId));
						otherIdSet.add(parentId);
					}
				}
			}
    		if(ObjectUtils.isNotEmpty(otherList)) {
    			list.addAll(otherList);
    		}
    	}
    }
    
    @ApiMethod(value="将资源列表解析为树结构", params = {@ApiField("资源列表"), @ApiField("父资源树"), @ApiField("展开路径")})
    public void parseDepartmentToTree(List<SystemDepartmentDataDo> list, SystemDepartmentTreeVo parent, String spreadPath) {
    	List<SystemDepartmentTreeVo> childList=new ArrayList<SystemDepartmentTreeVo>();
    	SystemDepartmentTreeVo treeNode;
    	for (SystemDepartmentDataDo department : list) {
			if(ObjectUtils.isEmpty(department.getParentId())) {
				continue;
			}
    		if(department.getParentId().equals(parent.getId())) {
    			treeNode=new SystemDepartmentTreeVo(department.getId(), department.getName());
    			if(ObjectUtils.isNotEmpty(spreadPath) && StringUtils.contains(spreadPath, department.getId()+"", "\\.")){
    				treeNode.setSpread(true);
    			}
    			childList.add(treeNode);
    			parseDepartmentToTree(list, treeNode, spreadPath);
    		}
		}
    	if(ObjectUtils.isNotEmpty(childList)) {
    		parent.setChildren(childList);
    	}
    }
    
    @ApiMethod(value="获取部门id的完整path", params = {@ApiField("资源id")}, returns = @ApiField("资源的完整path"))
    public String getCompletePath(Long id) {
    	if(ObjectUtils.isNotEmpty(id)){
			SystemDepartmentDataDo parent=this.findById(id);
			if(ObjectUtils.isNotEmpty(parent)) {
				if(ObjectUtils.isNotEmpty(parent.getParentPath())) {
					return parent.getParentPath()+parent.getId()+".";
				}else {
					return "."+parent.getId()+".";
				}
			}
		}
    	return null;
    }
    
    @ApiMethod(value="插入数据前设置默认值", params = {@ApiField("插入的数据")})
    public void setInsertDefault(SystemDepartmentInsertDo insert) {
    	SystemDepartmentSearchDo search=new SystemDepartmentSearchDo();
    	if(ObjectUtils.isEmpty(insert.getParentId())) {
    		Sql sql=Sql.createSql();
    		sql.addWhere(Sql.LOGIC_AND, "parent_id_", Sql.COMPARE_IS, "null");
    		search.setSql(sql);
    	}else {
    		search.setParentId(insert.getParentId());
    	}
    	insert.setSort(this.findCount(search)+1);
    }
    
    @ApiMethod(value="部门id是否已存在", params = {@ApiField("部门id")}, returns = @ApiField("是否存在，true：已存在，false：不存在"))
    public boolean existsById(Long id) {
    	return ObjectUtils.isNotEmpty(this.findById(id));
    }
    
    @ApiMethod(value="部门编码是否已存在", params = {@ApiField("部门编码")}, returns = @ApiField("是否存在，true：已存在，false：不存在"))
    public boolean existsByCode(String code) {
    	SystemDepartmentSearchDo search=new SystemDepartmentSearchDo();
    	search.setCode(code);
    	return this.findCount(search)>0;
    }
    
    @ApiMethod(value="部门名称是否已存在", params = {@ApiField("部门名称"), @ApiField("父部门id"), @ApiField("排除id")}, returns = @ApiField("是否存在，true：已存在，false：不存在"))
    public boolean existsByName(String name, Long parentId, Long excludeId) {
    	SystemDepartmentSearchDo search=new SystemDepartmentSearchDo();
    	search.setName(name);
    	search.setParentId(parentId);
    	this.addWhereNotEquals(search, "t.id_", excludeId, null);
    	return this.findCount(search)>0;
    }
    
    @ApiMethod(value="部门名称路径是否已存在", params = {@ApiField("部门名称路径，格式如：AA/BB/CC")}, returns = @ApiField("是否存在，true：已存在，false：不存在"))
    public boolean existsByNamePath(String namePath, Boolean excelExistsPath) {
    	if(excelExistsPath) {
    		return true;
    	}
    	SystemDepartmentDataDo department=null;
    	String[] nameArray=namePath.split("/");
    	SystemDepartmentSearchDo search;
    	String name;
    	for (int i = 0, length=nameArray.length; i < length; i++) {
    		name=nameArray[i].trim();
    		if(i==0) {
				search=new SystemDepartmentSearchDo();
				search.setName(name);
				this.addWhereNull(search, "parent_id_", true);
				department=this.findFirst(search, String.format("%s（%s）", "部门名称", name));
			}else {
				if(ObjectUtils.isEmpty(department)) {
					return false;
				}
				search=new SystemDepartmentSearchDo();
				search.setName(name);
				search.setParentId(department.getId());
				department=this.findFirst(search, String.format("%s（%s）下%s（%s）", "部门", department.getName(), "部门名称", name));
			}
		}
    	return ObjectUtils.isNotEmpty(department);
    }
    
    @ApiMethod(value="判断是否存在下属部门", params = {@ApiField("部门id")}, returns = @ApiField("是否存在，true：存在，false：不存在"))
    public boolean existsChild(long parentId) {
    	SystemDepartmentSearchDo search=new SystemDepartmentSearchDo();
    	search.setParentId(parentId);
    	return this.findCount(search)>0;
    }
    
    @ApiMethod(value="获取最大排序值（数据库最大值+1）", params = {@ApiField("父部门")}, returns = @ApiField("最大排序值"))
    public int findMaxSort(Long parentId) {
    	SystemDepartmentSearchDo search=new SystemDepartmentSearchDo();
    	search.setParentId(parentId);
		return this.findCount(search)+1;
    }
    
    @ApiMethod(value="根据部门名称路径查询部门", params = {@ApiField("部门名称路径，格式如：AA/BB/CC")}, returns = @ApiField("部门信息"))
    public SystemDepartmentDataDo findByNamePath(String namePath) {
    	SystemDepartmentDataDo department=null;
    	String[] nameArray=namePath.split("/");
    	SystemDepartmentSearchDo search;
    	String name;
    	for (int i = 0, length=nameArray.length; i < length; i++) {
    		name=nameArray[i].trim();
    		if(i==0) {
				search=new SystemDepartmentSearchDo();
				search.setName(name);
				this.addWhereNull(search, "parent_id_", true);
				department=this.findFirst(search, String.format("%s（%s）", "部门名称", name));
			}else {
				if(ObjectUtils.isEmpty(department)) {
					return null;
				}
				search=new SystemDepartmentSearchDo();
				search.setName(name);
				search.setParentId(department.getId());
				department=this.findFirst(search, String.format("%s（%s）下%s（%s）", "部门", department.getName(), "部门名称", name));
			}
		}
    	return department;
    }
}
